﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using Pixysoft.Framework.Verifications;
using Pixysoft.Collections;

namespace Pixysoft.Framework.Comet.Core
{
    /// <summary>
    /// 广播请求 内部包含了一个实际的cometrequest
    /// 用于多个链接监听一个号码的情况 = 广播
    /// 其本身是一个符合cometRequest的请求，同时使用了自身的时间戳获取内置的request的信息，实现广播模式
    /// </summary>
    class CometBroadcastRequest : CometRequest, ICometRequest
    {
        private ICometRequest cometRequest = null;


        public CometBroadcastRequest(ICometRequest request, string sendercode)
            : base(sendercode)
        {
            this.cometRequest = request;
        }


        public override int MessageCount
        {
            get
            {
                return cometRequest.MessageCount;
            }
        }

        /// <summary>
        /// 如果是持久数据 则对比时间戳，存在返回； 如果是普通数据，则删除数据后返回。
        /// </summary>
        /// <param name="timestamp"></param>
        /// <returns></returns>
        public override ICometMessage GetNextMessage()
        {
            return GetNextMessage(this.LastMessageTimeStamp);
        }

        public override ICometMessage GetNextMessage(long lastMessageTimeStamp)
        {
            ICometMessage message = cometRequest.GetNextMessage(lastMessageTimeStamp);

            //更新自己的，和cometReqeust无关

            UpdateLastPickupDate();

            if (message != null)
                SetLastMessageTimeStamp(new ICometMessage[] { message });

            return message;
        }

        public override ICometMessage GetLastMessage()
        {
            ICometMessage message = cometRequest.GetLastMessage();

            //更新自己的，和cometReqeust无关

            UpdateLastPickupDate();

            if (message != null)
                SetLastMessageTimeStamp(new ICometMessage[] { message });

            return message;
        }

        public override ICometMessage[] GetAllMessages()
        {
            ICometMessage[] messages = cometRequest.GetAllMessages();

            //更新自己的，和cometReqeust无关

            UpdateLastPickupDate();

            SetLastMessageTimeStamp(messages);

            return messages;
        }

        public override long AddMessages(params ICometMessage[] newmessages)
        {
            // do nothing

            return -1;
        }

        public override void ClearMessages()
        {
            //do nothing
        }

        public override void Visit(ICometRequestPool pool)
        {
            pool.Visit(SenderCode, this);

            cometRequest.Visit(pool);
        }
    }
}
